import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
//  vant 按需自动引入
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from 'unplugin-vue-components/resolvers';
import autoprefixer from 'autoprefixer'
import { viteVConsole } from 'vite-plugin-vconsole'
import viteCompression from 'vite-plugin-compression'

import { resolve } from "path";

export default (({ command, mode }) => {

  const root = process.cwd()
  const env = loadEnv(mode, root)

  return defineConfig({
    base: env.VITE_APP_PUBLIC_PATH,
    // 兼容 Cli
    define: {
      'process.env.VUE_APP_API_FILE_BASE_URL': JSON.stringify(env.VITE_APP_API_FILE_BASE_URL),
      'process.env.VUE_APP_API_BASE_URL': JSON.stringify(env.VITE_APP_API_BASE_URL),
      'process.env.VUE_APP_PUBLIC_PATH': JSON.stringify(env.VITE_APP_PUBLIC_PATH),
      'process.env.VITE_API_API_IMAGE_URL': JSON.stringify(env.VITE_API_API_IMAGE_URL),
      'process.env.VITE_APP_API_APPID': JSON.stringify(env.VITE_APP_API_APPID),
      'process.env.VITE_APP_API_HOST': JSON.stringify(env.VITE_APP_API_HOST)
    },
    plugins: [
      vue(),
      AutoImport({
        resolvers: [VantResolver()],
      }),
      Components({
        resolvers: [VantResolver()],
      }),
      viteVConsole({
        entry: [resolve(__dirname, 'src/main.js')],
        localEnabled: command === 'serve',
        enabled: false,
        config: {
          maxLogNumber: 1000,
          theme: 'light',
        },
      }),
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: 'gzip',
        ext: '.gz'
      }),
    ],
    resolve: {
      // 配置路径别名
      alias: {
        "@": resolve(__dirname, "./src"),
        "@utils": resolve(__dirname, './src/utils'),
        "@assets": resolve(__dirname, './src/assets'),
        "@components": resolve(__dirname, './src/components'),
        "@router": resolve(__dirname, './src/router'),
        "@api": resolve(__dirname, './src/api'),
        "@store": resolve(__dirname, './src/store'),
        "@style": resolve(__dirname, './src/style'),
        "@mixin": resolve(__dirname, './src/style/mixin.scss'),
        '@colors': resolve(__dirname, './src/style/colors.scss')
      },
    },
    css: {
      postcss: {
        plugins: [
          autoprefixer({ // 自动添加前缀
            overrideBrowserslist: [
              "Android 4.1",
              "iOS 7.1",
              "Chrome > 31",
              "ff > 31",
              "ie >= 8"
              //'last 2 versions', // 所有主流浏览器最近2个版本
            ],
            grid: true
          })
        ]
      }
    },
    // 配置后才能让编译后的vue路径被正确识别
    manifest: true,
    build: {
      cssCodeSplit: true, // css 代码分割
      chunkSizeWarningLimit: 2048, // 单个 css 文件超过 2048 字节时会显示警告
      terserOptions: {
        // minify 为terser生效 若minify为esbuild 则需要走esbuild的配置
        compress: {
          drop_console: mode === "production", // 生产环境去除console
          drop_debugger: mode === "production", // 生产环境去除debugger
        },
      },
      rollupOptions: {
        // rollup 打包配置
        output: {
          // 静态资源打包区分文件夹
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]",
          manualChunks(id) {
            // node_modules的包逐个打包
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          },
        },
      },
    },
    server: {
      host: "0.0.0.0",
      port: 8991,
      // 是否开启 https
      https: false,
      // 服务启动时是否自动打开浏览器
      open: true,
      // 允许跨域
      cors: true,
      //  热更新
      // hmr: true,
      // 设置反向代理，跨域
      proxy: {
        "/api": {
          // 后台地址
          // target: "http://58.222.146.13:8081/dev",
          target: "http://192.168.0.78:8083",
          // target: "http://192.168.0.75:8083",
          changeOrigin: true,
          // rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
  });
});
